package com.ranshiyan.controller;

import com.ranshiyan.entity.User;
import com.ranshiyan.entity.UserFile;
import com.ranshiyan.service.UserFileService;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private UserFileService userFileService;

    @Value("${upload.dir}")
    private String uploadPath;

    @GetMapping("delete")
    public String delete(String id) throws FileNotFoundException {

        UserFile byId = userFileService.findById(id);
        //删除文件
        String realpath = ResourceUtils.getURL("classpath:").getPath()+"/static"+byId.getPath();
        File file = new File(realpath, byId.getNewFileName());
        if(file.exists())file.delete();

        userFileService.delete(id);
        return "redirect:/file/findAll";
    }

    /**
     * 文件下載
     */
    @GetMapping("download")
   public void download(String openStyle,String id, HttpServletResponse response) throws IOException {
        //打开方式
        openStyle = openStyle==null?"attachment":openStyle;

        UserFile userFile = userFileService.findById(id);
        //更新下载次数
        if(openStyle.equals("attachment")){
            userFile.setDowncounts(userFile.getDowncounts()+1);
            userFileService.update(userFile);
        }
        String realpath = ResourceUtils.getURL("classpath:").getPath()+"/static"+userFile.getPath();
        //获取文件输入流
        FileInputStream fileInputStream = new FileInputStream(new File(realpath, userFile.getNewFileName()));
        //附件下载
        response.setHeader("content-disposition",openStyle+";fileName="+ URLEncoder.encode(userFile.getOldFileName(),"UTF-8"));
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();

        IOUtils.copy(fileInputStream,outputStream);
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
    }

    /**
     * 上传文件保存到数据库中
     */
    @PostMapping("upload")
    public String upload(MultipartFile aaa,HttpSession session) throws IOException {
        //文件原始名称
        String originalFilename = aaa.getOriginalFilename();

        User user = (User)session.getAttribute("user");

        //获取文件后缀
        String extension = "."+FilenameUtils.getExtension(aaa.getOriginalFilename());
        //生成新的文件名称
        String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ UUID.randomUUID().toString().replace("-","")+extension;

        //文件的大小
        Long size = aaa.getSize();
        //文件类型
        String contentType = aaa.getContentType();

        //根据日期生成目录
        String realPath = ResourceUtils.getURL("classpath:").getPath()+"/static/files";
        String dataformat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dateDirPath = realPath+"/"+ dataformat;
        File dateDir = new File(dateDirPath);
        if(!dateDir.exists())dateDir.mkdirs();

        //文件上传
        aaa.transferTo(new File(dateDir,newFileName));
        
        //将文件信息放入数据库中保存
        UserFile userFile = new UserFile();


        userFile.setOldFileName(originalFilename).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size)).setType(contentType)
        .setPath("/files/" +dataformat).setUserId(user.getId());
        userFileService.save(userFile);
        return "redirect:/file/findAll";
    }

    /**
     * 展示所有文件信息
     */
    @GetMapping("findAll")
    public String findAll(HttpSession session, Model model){
        //session获取用户id
        User user = (User)session.getAttribute("user");
        List<UserFile> byUserId = userFileService.findByUserId(user.getId());

        model.addAttribute("files",byUserId);
        return "showAll";
    }
}
